package com.test45_JUC;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Demo16_Collections {

    public static void main(String[] args) {
        // test1();
        test2();
    }

    /**
     * 传统ArrayList处理多线程时，出现的问题
     */
    public static void test1() {
        List<String> list = new ArrayList<>();
        for (int x = 0; x < 10; x++) {
            new Thread(() -> {
                for (int y = 0; y < 10; y++) {
                    list.add("【" + Thread.currentThread().getName() + "】www.yootk.com");
                    System.out.println(list);
                }
            }, "集合操作线程-"+x).start();
        }
    }

    /**
     * Collections提供的同步集合处理方法
     * 会变为同步集合，效率降低
     */
    public static void test2() {
        List<String> list = new ArrayList<>();
        List<String> syncList = Collections.synchronizedList(list);
        for (int x = 0; x < 10; x++) {
            new Thread(() -> {
                for (int y = 0; y < 10; y++) {
                    syncList.add("【" + Thread.currentThread().getName() + "】www.yootk.com");
                    System.out.println(syncList);
                }
            }, "集合操作线程-"+x).start();
        }
    }
}
